import { defineStore } from 'pinia'
import { userPropsConfig } from './constant'
import { loginAsync } from '@/api/login/login'

const userProps: userPropsConfig = {
  id: 'user', // id必填，且需要唯一
  state: () => {
    return {
      name: null,
      email: null,
      token: null,
    }
  },
  actions: {
    updateUserInfo({ name, email, token }) {
      if (name) {
        this.name = name;
      }
      if (email) {
        this.email = email;
      }
      if (token) {
        this.token = token;
      }
    },
    async login(email, password) {
      try {
        const result = await loginAsync({ email, password })
        if (result.data.status) {
          this.token = result.data.token
          window.localStorage.setItem("__token__", this.token);
          window.localStorage.setItem("email", email);
        } else {
          window.localStorage.setItem("__token__", '');
          throw {
            message: result.data.message,
          }
        }
      } catch (error: any) {
        throw {
          error,
          message: error?.message !== 'post请求出错' ? error.message : '邮箱或密码错误'
        }
      }

    }
  }
}

export const useUserStore = defineStore(userProps)
